
package com.jf.cloud.search.listener;

import cn.throwx.canal.gule.CanalGlue;
import com.alibaba.fastjson.JSON;
import com.jf.cloud.common.rocketmq.config.RocketMqConstant;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zz
 * @date 2021/02/03
 */
@Component
@RocketMQMessageListener(topic = RocketMqConstant.CANAL_TOPIC,consumerGroup = RocketMqConstant.CANAL_TOPIC)
public class BaseCanalListener implements RocketMQListener<String> {

    private static final Logger log = LoggerFactory.getLogger(BaseCanalListener.class);

    private static Pattern PATTERN = Pattern.compile("\\w+[_]{1}[\\d]+");
    private static String TABLE = "table";
    private static String DATABASE = "database";

    @Autowired
    private CanalGlue canalGlue;

    @Override
    public void onMessage(String message) {
        log.info("get mq message:" + message);
        Map map = JSON.parseObject(message, Map.class);
        map.put(TABLE, handleTableOrDatabaseName(map.get(TABLE)));
        map.put(DATABASE, handleTableOrDatabaseName(map.get(DATABASE)));
        canalGlue.process(JSON.toJSONString(map));
    }

    private String handleTableOrDatabaseName(Object o) {
        if (Objects.isNull(o)) {
            return null;
        }
        String name = o.toString();
        Matcher databaseMatcher = PATTERN.matcher(name);
        if (databaseMatcher.matches()) {
            name = name.substring(0, name.lastIndexOf("_"));
        }
        return name;
    }
}
